﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="AccessListExtensions.cs" company="Marcin Jastrzebski">
//   Copyright (c) Marcin Jastrzebski (marcin@marcinj.net)
// </copyright>
// <summary>
//   The access list extensions.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace mPassRT.Utilities
{
    using System;

    using Windows.Storage;
    using Windows.Storage.AccessCache;

    /// <summary>The access list extensions.</summary>
    public static class AccessListExtensions
    {
        #region Public Methods and Operators

        /// <summary>The ensure path safe to use.</summary>
        /// <param name="storageItem">The storage item.</param>
        /// <returns>The <see cref="IDisposable"/>.</returns>
        public static IDisposable EnsurePathSafeToUse(this IStorageItem storageItem)
        {
            return new AccessListEntryLifetimeManager(storageItem);
        }

        #endregion

        /// <summary>The access list entry lifetime manager.</summary>
        private class AccessListEntryLifetimeManager : IDisposable
        {
            #region Fields

            /// <summary>The token.</summary>
            private readonly string token;

            #endregion

            #region Constructors and Destructors

            /// <summary>Initializes a new instance of the <see cref="AccessListEntryLifetimeManager"/> class.</summary>
            /// <param name="storageItem">The storage item.</param>
            public AccessListEntryLifetimeManager(IStorageItem storageItem)
            {
                this.token = StorageApplicationPermissions.FutureAccessList.Add(storageItem);
            }

            #endregion

            #region Public Methods and Operators

            /// <summary>The dispose.</summary>
            public void Dispose()
            {
                if (StorageApplicationPermissions.FutureAccessList.ContainsItem(this.token))
                {
                    StorageApplicationPermissions.FutureAccessList.Remove(this.token);
                }
            }

            #endregion
        }
    }
}